import {
  deletePageById,
  deleteUserById,
  editPageData,
  editUserData,
  newPageData,
  newUserData,
  postPageListData,
  postUsersListData
} from '@/service/main/system/system'
import type { ISystemState } from '@/types/system'
import { defineStore } from 'pinia'
import { useMainStore } from '../main'

export const useSystemStore = defineStore('system_store', {
  state: (): ISystemState => ({
    userList: [],
    usersTotalCount: 0,
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    // 获取列表数据
    async postUserListAction(queryInfo: any) {
      const res = await postUsersListData(queryInfo)
      this.userList = res.data.list
      this.usersTotalCount = res.data.totalCount
    },
    // 删除数据
    async deleteUserById(id: number) {
      await deleteUserById(id)
      // 重新请求数据
      this.postUserListAction({ offset: 0, size: 10 })
    },
    // 新建数据
    async newUserDataAction(userInfo: any) {
      await newUserData(userInfo)
      // 重新请求数据
      this.postUserListAction({ offset: 0, size: 10 })
    },
    // 编辑数据
    async editUserDataAction(id: number, userInfo: any) {
      await editUserData(id, userInfo)
      // 重新请求数据
      this.postUserListAction({ offset: 0, size: 10 })
    },

    // 获取页面的列表数据
    async postPageListAction(pageName: string, queryInfo: any) {
      const res = await postPageListData(pageName, queryInfo)
      this.pageList = res.data.list
      this.pageTotalCount = res.data.totalCount

      // 重新获取main数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    // 删除页面的某个数据
    async deletePageById(pageName: string, id: number) {
      await deletePageById(pageName, id)
      this.postPageListAction(pageName, { offset: 0, size: 10 })

      // 重新获取main数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    // 新建页面数据
    async newPageDataAction(pageName: string, pageInfo: any) {
      await newPageData(pageName, pageInfo)
      this.postPageListAction(pageName, { offset: 0, size: 10 })

      // 重新获取main数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    // 编辑数据
    async editPageDataAction(pageName: string, id: number, pageInfo: any) {
      await editPageData(pageName, id, pageInfo)
      // 重新请求数据
      this.postUserListAction({ offset: 0, size: 10 })

      // 重新获取main数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    }
  }
})
